<template>
  <BasicModal
    :visible="visible"
    title="选择节点"
    :loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-tree
      v-model:expanded-keys="expandedKeys"
      v-model:selected-keys="selectedKeys"
      v-model:checked-keys="checkedKeys"
      :tree-data="treeData"
      :checkable="true"
      :checkStrictly="true"
      show-icon
    >
      <template #switcherIcon="{ switcherCls }">
        <down-outlined :class="switcherCls" />
      </template>
      <template #icon="{ type }">
        <template v-if="type === 'system'">
          <appstore-add-outlined />
        </template>
        <template v-else>
          <database-outlined />
        </template>
      </template>
    </a-tree>
  </BasicModal>
</template>

<script>
  import { Tree, message } from 'ant-design-vue'
  import { useRouter } from 'vue-router'
  import { getDescendants } from '/@/api/module/module'
  import { getTopoModuleList } from '/@/api/module/topoModule'
  import { BasicModal } from '/@/components/Modal'
  import { useModuleStoreWithOut } from '/@/store/modules/module'
  import { DownOutlined, DatabaseOutlined, AppstoreAddOutlined } from '@ant-design/icons-vue'

  export default {
    components: {
      'a-tree': Tree,
      'down-outlined': DownOutlined,
      'appstore-add-outlined': AppstoreAddOutlined,
      'database-outlined': DatabaseOutlined,
      BasicModal,
    },
    props: {
      visible: Boolean,
      topoView: Number,
    },
    emits: ['ok', 'cancel'],
    data() {
      return {
        store: useModuleStoreWithOut(),
        router: useRouter(),
        loading: false,
        treeData: [],
        expandedKeys: [],
        selectedKeys: [],
        checkedKeys: [],
      }
    },
    watch: {
      expandedKeys() {
        console.log('expandedKeys', this.expandedKeys)
      },
      selectedKeys() {
        console.log('selectedKeys', this.selectedKeys)
      },
      checkedKeys() {
        console.log('checkedKeys', this.checkedKeys)
      },
    },
    mounted() {
      if (this.store.getRoot.id != 0) {
        this.loading = true
        getDescendants({ root: this.store.getRoot.id })
          .then((data) => {
            this.onGetDescendants(data)
          })
          .catch((e) => {
            console.error('get child nodes failed:', e)
            message.error('get child nodes failed')
            this.loading = false
          })
      }
    },
    methods: {
      handleCancel: function () {
        this.$emit('cancel')
      },
      handleOk: function () {
        this.$emit('ok', this.checkedKeys)
      },
      onNodeChecked(node) {
        console.log(node)
      },
      onGetDescendants(data) {
        let root = {
          title: data.parent.name,
          key: data.parent.name,
          id: data.parent.moduleId,
          type: data.parent.moduleType,
          desc: data.parent.desc,
          children: [],
        }
        let nodes = []
        this.makeTreeData(root, data, nodes)
        this.treeData.push(root)
        this.setExpandedKeys(nodes)
        this.setSelectedKeys()
      },
      makeTreeData(node, modules, nodes) {
        if (!modules || !node) return

        // expand keys
        nodes.push(node)

        // find children
        for (let mod of modules) {
          if (mod.parentName === node.key) {
            node.children.push({
              title: mod.name,
              key: mod.name,
              id: mod.moduleId,
              type: mod.moduleType,
              desc: mod.desc,
              children: [],
            })
          }
        }

        // make children
        for (let child of node.children) {
          this.makeTreeData(child, modules, nodes)
        }
      },
      setExpandedKeys(nodes) {
        this.expandedKeys = []
        for (let node of nodes) {
          this.expandedKeys.push(node.key)
        }
      },
      setSelectedKeys() {
        getTopoModuleList({ view: this.topoView })
          .then((data) => {
            if (data && data.modules) {
              for (let module of data.modules) {
                this.checkedKeys.push(module.name)
              }
            }
            this.loading = false
          })
          .catch((e) => {
            console.log('get module list failed:', e)
          })
      },
    },
  }
</script>
